using System;
using System.Collections.Generic;
using System.Text;

namespace Wrath.Xml.Objects
{
    public class Position : IElementContainer
    {
        private int? x = null;

        public int? X
        {
            get { return x; }
            set { x = value; }
        }

        private int? y = null;

        public int? Y
        {
            get { return y; }
            set { y = value; }
        }

        public Position(Element element)
        {
            sourceElement = element;

            Element subElement = element.FindFirstElement("x", false);
            if (subElement != null)
            {
                try
                {
                    x = Convert.ToInt32(subElement.Value);
                }
                catch
                {
                    x = null;
                }
            }

            subElement = element.FindFirstElement("y", false);
            if (subElement != null)
            {
                try
                {
                    y = Convert.ToInt32(subElement.Value);
                }
                catch
                {
                    y = null;
                }
            }
        }

        #region IElementContainer Members

        private Element sourceElement;
        public Element SourceElement
        {
            get { return sourceElement; }
        }

        public void Commit()
        {
            sourceElement = new Element("position");

            if (x != null)
            {
                Element xElement = new Element("x", x.ToString());
                sourceElement.ChildElements.Add(xElement);
            }

            if (y != null)
            {
                Element yElement = new Element("y", y.ToString());
                sourceElement.ChildElements.Add(yElement);
            }
        }

        #endregion
    }
}
